package com.example.service.impl;

import com.example.calculator.RiskIndicatorCalculator;
import com.example.dto.RiskIndicatorDTO;
import com.example.model.RiskIndicator;
import com.example.service.RiskCalculationService;
import com.example.service.RiskIndicatorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 风控指标计算服务实现类
 * 整合风控指标计算器和风控指标服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RiskCalculationServiceImpl implements RiskCalculationService {

    private final RiskIndicatorCalculator calculator;
    private final RiskIndicatorService riskIndicatorService;
    private final Random random = new Random();

    @Override
    public RiskIndicatorDTO calculateTransactionRiskIndicator(String userId) {
        log.info("Calculating transaction risk indicator for user: {}", userId);
        
        // 模拟交易数据
        int transactionCount = random.nextInt(20) + 1; // 1-20次交易
        double transactionAmount = random.nextDouble() * 5000; // 0-5000金额
        int failedAttempts = random.nextInt(5); // 0-4次失败尝试
        
        // 计算风险指标
        RiskIndicatorCalculator.CalculationResult result = calculator.calculateTransactionRisk(
                userId, transactionCount, transactionAmount, failedAttempts);
        
        // 创建风控指标DTO
        RiskIndicatorDTO indicatorDTO = RiskIndicatorDTO.builder()
                .id(UUID.randomUUID().toString())
                .userId(userId)
                .type("TRANSACTION_RISK")
                .name("交易风险指标")
                .value(result.getRiskScore())
                .riskLevel(result.getRiskLevel().name())
                .calculatedAt(LocalDateTime.now())
                .validUntil(LocalDateTime.now().plusDays(7))
                .source("SYSTEM_CALCULATION")
                .description("系统计算的交易风险指标")
                .attributes(result.getAttributes())
                .build();
        
        // 保存并返回风控指标
        return riskIndicatorService.saveIndicator(indicatorDTO);
    }

    @Override
    public RiskIndicatorDTO calculateLoginRiskIndicator(String userId) {
        log.info("Calculating login risk indicator for user: {}", userId);
        
        // 模拟登录数据
        int loginAttempts = random.nextInt(10) + 1; // 1-10次登录尝试
        int failedLogins = random.nextInt(3); // 0-2次失败登录
        boolean unusualLocationLogin = random.nextBoolean(); // 是否有异常地点登录
        boolean unusualTimeLogin = random.nextBoolean(); // 是否有异常时间登录
        
        // 计算风险指标
        RiskIndicatorCalculator.CalculationResult result = calculator.calculateLoginRisk(
                userId, loginAttempts, failedLogins, unusualLocationLogin, unusualTimeLogin);
        
        // 创建风控指标DTO
        RiskIndicatorDTO indicatorDTO = RiskIndicatorDTO.builder()
                .id(UUID.randomUUID().toString())
                .userId(userId)
                .type("LOGIN_RISK")
                .name("登录风险指标")
                .value(result.getRiskScore())
                .riskLevel(result.getRiskLevel().name())
                .calculatedAt(LocalDateTime.now())
                .validUntil(LocalDateTime.now().plusDays(3))
                .source("SYSTEM_CALCULATION")
                .description("系统计算的登录风险指标")
                .attributes(result.getAttributes())
                .build();
        
        // 保存并返回风控指标
        return riskIndicatorService.saveIndicator(indicatorDTO);
    }

    @Override
    public RiskIndicatorDTO calculateAccountRiskIndicator(String userId) {
        log.info("Calculating account risk indicator for user: {}", userId);
        
        // 模拟账户数据
        int accountAge = random.nextInt(365) + 1; // 1-365天账户年龄
        boolean recentPasswordChange = random.nextBoolean(); // 是否最近修改密码
        boolean hasTwoFactorAuth = random.nextBoolean(); // 是否启用双因素认证
        int suspiciousActivities = random.nextInt(5); // 0-4次可疑活动
        
        // 计算风险指标
        RiskIndicatorCalculator.CalculationResult result = calculator.calculateAccountRisk(
                userId, accountAge, recentPasswordChange, hasTwoFactorAuth, suspiciousActivities);
        
        // 创建风控指标DTO
        RiskIndicatorDTO indicatorDTO = RiskIndicatorDTO.builder()
                .id(UUID.randomUUID().toString())
                .userId(userId)
                .type("ACCOUNT_RISK")
                .name("账户风险指标")
                .value(result.getRiskScore())
                .riskLevel(result.getRiskLevel().name())
                .calculatedAt(LocalDateTime.now())
                .validUntil(LocalDateTime.now().plusDays(30))
                .source("SYSTEM_CALCULATION")
                .description("系统计算的账户风险指标")
                .attributes(result.getAttributes())
                .build();
        
        // 保存并返回风控指标
        return riskIndicatorService.saveIndicator(indicatorDTO);
    }

    @Override
    public RiskIndicatorDTO calculateOverallRiskIndicator(String userId) {
        log.info("Calculating overall risk indicator for user: {}", userId);
        
        // 计算各个风险指标
        RiskIndicatorDTO transactionRisk = calculateTransactionRiskIndicator(userId);
        RiskIndicatorDTO loginRisk = calculateLoginRiskIndicator(userId);
        RiskIndicatorDTO accountRisk = calculateAccountRiskIndicator(userId);
        
        // 计算综合风险分数 (加权平均)
        double transactionWeight = 0.4;
        double loginWeight = 0.3;
        double accountWeight = 0.3;
        
        double overallScore = 
                transactionRisk.getValue() * transactionWeight +
                loginRisk.getValue() * loginWeight +
                accountRisk.getValue() * accountWeight;
        
        // 确定风险等级
        RiskIndicator.RiskLevel riskLevel;
        if (overallScore < 30) {
            riskLevel = RiskIndicator.RiskLevel.LOW;
        } else if (overallScore < 60) {
            riskLevel = RiskIndicator.RiskLevel.MEDIUM;
        } else if (overallScore < 80) {
            riskLevel = RiskIndicator.RiskLevel.HIGH;
        } else {
            riskLevel = RiskIndicator.RiskLevel.CRITICAL;
        }
        
        // 构建额外属性
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("transactionRiskId", transactionRisk.getId());
        attributes.put("transactionRiskScore", transactionRisk.getValue());
        attributes.put("transactionRiskLevel", transactionRisk.getRiskLevel());
        attributes.put("loginRiskId", loginRisk.getId());
        attributes.put("loginRiskScore", loginRisk.getValue());
        attributes.put("loginRiskLevel", loginRisk.getRiskLevel());
        attributes.put("accountRiskId", accountRisk.getId());
        attributes.put("accountRiskScore", accountRisk.getValue());
        attributes.put("accountRiskLevel", accountRisk.getRiskLevel());
        attributes.put("transactionWeight", transactionWeight);
        attributes.put("loginWeight", loginWeight);
        attributes.put("accountWeight", accountWeight);
        
        // 创建综合风控指标DTO
        RiskIndicatorDTO indicatorDTO = RiskIndicatorDTO.builder()
                .id(UUID.randomUUID().toString())
                .userId(userId)
                .type("OVERALL_RISK")
                .name("综合风险指标")
                .value(overallScore)
                .riskLevel(riskLevel.name())
                .calculatedAt(LocalDateTime.now())
                .validUntil(LocalDateTime.now().plusDays(3))
                .source("SYSTEM_CALCULATION")
                .description("系统计算的综合风险指标")
                .attributes(attributes)
                .build();
        
        // 保存并返回风控指标
        return riskIndicatorService.saveIndicator(indicatorDTO);
    }
}